package com.lingshi.shopping_goods_service.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.shopping.entity.Brand;
import com.lingshi.shopping.entity.Goods;
import com.lingshi.shopping.enums.ErrorEnums;
import com.lingshi.shopping.exception.BusException;
import com.lingshi.shopping.service.BrandService;
import com.lingshi.shopping_goods_service.mapper.BrandMapper;
import com.lingshi.shopping_goods_service.mapper.GoodsMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Brand findBrandById(Integer id) {
        if (id<=0){
            throw new BusException(ErrorEnums.PARAMS_ERROR);
        }
        return brandMapper.selectById(id);
    }

    @Override
    public List<Brand> findAll() {
        return brandMapper.selectList(null);
    }

    @Override
    public void add(Brand brand) {
        LambdaQueryWrapper<Brand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Brand::getName,brand.getName());
        Long count = brandMapper.selectCount(queryWrapper);
        if (count>0){
            throw new BusException(ErrorEnums.BRAND_EXISTS_ERROR);
        }
        brandMapper.insert(brand);
    }

    @Override
    public void update(Brand brand) {
        brandMapper.updateById(brand);
    }

    @Override
    public void delete(Long id) {
        /**
         * 判断商品表中是否有关联品牌
         *  1，有，不能删除
         *  2，没有,可以删除
         */
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getBrandId, id);
        Long count = goodsMapper.selectCount(queryWrapper);
        if (count>0){
            throw new BusException(ErrorEnums.GOODS_HAS_BRAND_ERROR);
        }
        brandMapper.deleteById(id);

    }

    @Override
    public Page<Brand> search(String name, int page, int size) {
        LambdaQueryWrapper<Brand> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(name)){
            queryWrapper.like(Brand::getName, name);
        }
        Page<Brand> objectPage = new Page<>(page, size);

        brandMapper.selectPage(objectPage, queryWrapper);

        return objectPage;
    }
}
